package com.qk.controller;


import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.dto.BusinessDto;
import com.qk.entity.Business;
import com.qk.service.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/businesses")
public class BusinessController {
    @Autowired
    private BusinessService businessService;

    //新增商机
    @PostMapping
    public Result addBusiness(@RequestBody Business business){
        log.info("新增商机:{}" , business);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        businessService.save(business);
        return Result.success();
    }

    //查询商机列表
    @GetMapping
    public Result listBusiness(BusinessDto businessDto){
        log.info("查询商机:{}" , businessDto);
        // 如果没有指定用户ID，则查询当前用户负责的商机
        PageResult<Business> page = businessService.lists(businessDto);
        return Result.success(page);
    }


    //分配商机
    @PutMapping("/assign/{businessId}/{userId}")
    public Result assign(@PathVariable Integer businessId,@PathVariable Integer userId){
        Business business = new Business();
        business.setId(businessId);
        business.setUserId(userId);
        business.setStatus(2);
        business.setUpdateTime(LocalDateTime.now());
        businessService.updateById(business);
        return Result.success();
    }

    //根据ID查询商机
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        log.info("查询商机id:{}" , id);
        Business business = businessService.getBusinessById(id);
        return Result.success(business);
    }

    //跟进商机
    @PutMapping
    public Result trackBusiness(@RequestBody Business business){
        log.info("跟进商机:{}" , business);
        businessService.trackBusiness(business);
        return Result.success();
    }
    //踢回公海
    @PutMapping("/back/{id}")
    public Result backToPool(@PathVariable Integer id){
        log.info("踢回公海:{}" , id);
        Business business = new Business();
        business.setId(id);
        business.setStatus(4);
        business.setUserId(null);
        business.setUpdateTime(LocalDateTime.now());
        businessService.updateById(business);
        return Result.success();
    }
    @PostMapping("/toCustomer/{id}")
    public Result toCustomer(@PathVariable Integer id){
        log.info("转客户:{}" , id);
        businessService.toCustomer(id);
        return Result.success();
    }

    @GetMapping("/pool")
    public Result poolList(BusinessDto businessDto){
        log.info("查询商机:{}" , businessDto);
        PageResult<Business> page = businessService.poolList(businessDto);
        return Result.success(page);
    }

}
